package com.landking.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatTextView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.landking.R;
import com.landking.adapter.AlertKeyValueAdapter;
import com.landking.base.BaseMainFragment;
import com.landking.db.table.LK_DATADIC_M;
import com.landking.db.table.LK_PIC_M;
import com.landking.home.pic.PicListFragment;
import com.landking.home.pic.adapter.PicnameAdapter;
import com.landking.view.alertview.AlertView;
import com.landking.view.loader.LatteLoader;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


/**
 *
 */
public class PicFragment extends BaseMainFragment implements View.OnClickListener {

    /**
     * UI
     */
    private View view;
    private FrameLayout containerFl;
    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private AppCompatTextView backTv;
    private AppCompatTextView titleTv;

    private ListView dataLv;
    private LinearLayout emptyLl;


    private List<LK_PIC_M> picList = new ArrayList<>();
    private List<LK_PIC_M> selectList = new ArrayList<>();
    private List<LK_DATADIC_M> picTypeLst;

    private PicnameAdapter nameAdapter;

    private AlertView mAlertViewExt;

    LK_DATADIC_M datadicM;// 默认第一个类型
    String dicname = "";// 选中的类型
    String diccode = "";// 类型code


    public static PicFragment newInstance() {
        Bundle args = new Bundle();
        PicFragment fragment = new PicFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static PicFragment newInstance(Bundle bundle) {
        Bundle args = bundle;
        PicFragment fragment = new PicFragment();
        fragment.setArguments(args);
        return fragment;
    }

    MyHandler handler;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<PicFragment> fragmentRef;

        public MyHandler(PicFragment fragment) {
            fragmentRef = new SoftReference<PicFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            PicFragment fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();
            // 处理UI 变化
            switch (msg.what) {
                case 0:
                    //fragment.showAddProSuc(bundle);
                    break;
                case 1:
                    // fragment.showAdapter(bundle);
                    break;
                case 2:
                    // fragment.showTzAdapter(bundle);
                    break;
            }
        }
    }

    /**
     * data
     */
    public PicFragment() {
    }

    // 获取传递过来的参数
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            // title = (String) arguments.get("title");// 需要改
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getActivity();

        // 不重复加载 做缓存处理
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_pic_layout, container, false);// 需要改
            this.initView();
            this.initData();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }


    // 初始化视图
    private void initView() {
        containerFl = (FrameLayout) view.findViewById(R.id.pic_container);// 需要改
        backBtn = (RelativeLayout) view.findViewById(R.id.top_navigation_rl_back);
        confirmBtn = (RelativeLayout) view.findViewById(R.id.top_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) view.findViewById(R.id.top_navigation_bt_confirm);
        backTv = (AppCompatTextView) view.findViewById(R.id.top_navigation_bt_back);
        titleTv = (AppCompatTextView) view.findViewById(R.id.top_navigation_tv_title);
        backBtn.setVisibility(View.INVISIBLE);
        confirmBtn.setVisibility(View.VISIBLE);
        backBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);

        emptyLl = (LinearLayout) view.findViewById(R.id.picwall_ll_empty);
        dataLv = (ListView) view.findViewById(R.id.picwall_ll_list);

    }

    private void initData() {

        titleTv.setText("图片");// 需要改
        confirmTv.setText(dicname + " >");
        confirmTv.setTag(diccode);
        confirmTv.setTextSize(14);
        confirmTv.setTextColor(getActivity().getResources().getColor(R.color.color_1DB974));

        dataLv.setEmptyView(emptyLl);


        picTypeLst = new ArrayList<>();

        // 获取所有的图片类型
        BmobQuery<LK_DATADIC_M> categoryBmobQuery = new BmobQuery<>();
        // categoryBmobQuery.addWhereEqualTo("pictype", pictype);
        categoryBmobQuery.setLimit(500); // 最多500条数据 设置大于500也只显示500条
        categoryBmobQuery.findObjects(new FindListener<LK_DATADIC_M>() {
            @Override
            public void done(List<LK_DATADIC_M> object, BmobException e) {
                if (e == null) {// 查询成功
                    picTypeLst = object;

                    // 设置默认选择的类型
                    if (picTypeLst != null && picTypeLst.size() > 0) {
                        datadicM = picTypeLst.get(0);
                        dicname = datadicM.getDicname();// 默认选中的类型
                        diccode = datadicM.getDiccode();// 默认类型code
                        confirmTv.setText(dicname + " >");
                        confirmTv.setTag(diccode);
                    }

                } else {// 查询成功
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });


        // 获取所有图片封面链接
        BmobQuery<LK_PIC_M> picMBmobQuery = new BmobQuery<>();
        // picMBmobQuery.addWhereEqualTo("pictype", pictype);//
        picMBmobQuery.addWhereGreaterThan("end", 1); // 设置end字段大于1
        picMBmobQuery.setLimit(500); // 最多500条数据 设置大于500也只显示500条
        // picMBmobQuery.order("pictitle");// 根据pictitle字段升序显示数据
        picMBmobQuery.findObjects(new FindListener<LK_PIC_M>() {
            @Override
            public void done(List<LK_PIC_M> object, BmobException e) {
                if (e == null) {// 查询成功
                    picList.clear();
                    picList.addAll(object);
                    selectList.clear();
                    selectList.addAll(object);
                    // adapter = new ImageAdapter(getActivity(), selectList);
                    // mImageGridView.setAdapter(adapter);

                    nameAdapter = new PicnameAdapter(getActivity(), selectList);
                    dataLv.setAdapter(nameAdapter);


                } else {// 查询成功
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        dataLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                LatteLoader.showLoading(getActivity());

                LK_PIC_M picM = selectList.get(position);
                PicListFragment fragment = new PicListFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("LK_PIC_M", picM);
                fragment.setArguments(bundle);
                if (fragment != null) {
                    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                    transaction.replace(R.id.pic_container, fragment);
                    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_navigation_rl_confirm://
                selectPictype(picTypeLst, (String) confirmTv.getTag());
                break;
        }
    }


    // 选择图片类型
    private void selectPictype(final List<LK_DATADIC_M> pictypeList, String pictype) {
        mAlertViewExt = new AlertView("请选择类型", null, null, null, null, getActivity(), AlertView.Style.Alert, null);
        ViewGroup extView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.layout_alert_list_form, null);
        ListView listview = (ListView) extView.findViewById(R.id.alert_list);
        AlertKeyValueAdapter keyValueAdapter = new AlertKeyValueAdapter(getActivity(), pictypeList,
                new String[]{"diccode", "dicname"}, pictype);
        listview.setAdapter(keyValueAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dicname = pictypeList.get(position).getDicname();
                diccode = pictypeList.get(position).getDiccode();
                confirmTv.setText(dicname + " >");
                confirmTv.setTag(diccode);
                selectList.clear();
                if ("-1".equals(diccode)) {// 全部
                    selectList.addAll(picList);
                } else {// 根据类型筛选
                    for (LK_PIC_M picM : picList) {
                        if ((picM.getPictype()).equals(dicname)) {
                            selectList.add(picM);
                        }
                    }
                }
                dataLv.setAdapter(nameAdapter);
                mAlertViewExt.dismiss();
            }
        });
        mAlertViewExt.addExtView(extView);
        mAlertViewExt.setCancelable(true).setOnDismissListener(null);
        mAlertViewExt.show();
    }


    // 判断是否是全部图片类型 否则展示全部
    private boolean getIsShowAllPicType() {
        if (!"-1".equals(diccode) && datadicM != null) {
            dicname = datadicM.getDicname();// 默认选中的类型
            diccode = datadicM.getDiccode();// 默认类型code
            confirmTv.setText(dicname + " >");
            confirmTv.setTag(diccode);
            selectList.clear();
            selectList.addAll(picList);
            dataLv.setAdapter(nameAdapter);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean allowBackPressed() {

        FragmentManager fm = getChildFragmentManager();
        if (fm.getBackStackEntryCount() > 0) {// 获取当前已加入Fragment回退栈中的fragment的数量。
            fm.popBackStack();
            return true;
        } else if (mAlertViewExt != null && mAlertViewExt.isShowing()) {// 判读是否有弹窗
            mAlertViewExt.dismiss();
            return true;
        } else if (getIsShowAllPicType()) {// 判断是否是全部图片类型 否则展示全部
            return true;
        }
        return super.allowBackPressed();
    }
}